package com.cn.lcc.util.sign;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.lang.StringUtils;

/**
 * @author lcc
 * @date 2017年6月12日
 * @备注 签名工具类
 */
public class SignUtil {

    public static String getSign(Map<String, String> params, String signKey) {
        SortedMap<String, String> orderedMap = new TreeMap<String, String>();
        Set<String> pKeys = params.keySet();
        for (String key : pKeys) {
            if (StringUtils.isNotEmpty(params.get(key))) {
                orderedMap.put(key, params.get(key));
            }
        }
        pKeys = orderedMap.keySet();
        List<String> temp = new ArrayList<String>();
        for (String key : pKeys) {
        	if (!"sign".equals(key)) {
                temp.add(key + "=" + orderedMap.get(key));
			}
        }
        System.out.println(Md5Util.GetMD5(StringUtils.join(temp.toArray(), "&") + signKey));
        return Md5Util.GetMD5(StringUtils.join(temp.toArray(), "&") + signKey);
    }

    public static boolean isValid(Map<String, String> params, String signKey) {
        String sign = params.get("sign");
        if (StringUtils.isEmpty(sign)) {
            return false;
        }
        params.remove("sign");
        String ssign = getSign(params, signKey);
        return ssign.equals(sign);
    }

    public static void main(String[] args) {
        Map<String, String> a = new HashMap<String, String>();
        a.put("dsa", "1");
        a.put("ser", "2");
        a.put("acf", "3");
        a.put("aaf", "4");
        a.put("acf1", "3");
        System.out.println(SignUtil.getSign(a, "1223244"));
        a.put("sign", "0c55e11c959b78184f6ab967d2ab0962");
        System.out.println(isValid(a, "1223244"));
    }
}
